package com.fxwater.api;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSONObject;
import com.fxwater.common.core.domain.AjaxResult;
import com.fxwater.common.exception.BusinessException;

/**
 * @ClassName: GlobalExceptionHandler.java
 * @Description: 异常处理
 *
 * @author: tzh
 * @date: 2018年6月2日 下午11:17:19
 *
 */
@ControllerAdvice
public class ApiGlobalExceptionHandler {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    public static final String DEFAULT_ERROR_VIEW = "error";

    /**
     * @Function: exp
     * @Description: 基于@ExceptionHandler异常处理
     *
     * @param: @param request
     * @param: @param response
     * @param: @param ex
     * @param: @return
     * @return: String
     * @throws
     */
    @ExceptionHandler(Exception.class)
    public ModelAndView exp(HttpServletRequest request, HttpServletResponse response, Exception ex) {
//        if (!isAjax(request)) {
//            ModelAndView mav = new ModelAndView();
//            mav.addObject("exception", ex);
//            mav.addObject("url", request.getRequestURL());
//            
//            mav.setViewName(DEFAULT_ERROR_VIEW);
//            return mav;
//        }
        
        AjaxResult errorInfoResp = null;
        if (ex instanceof BusinessException) {
            BusinessException exception = (BusinessException) ex;
            errorInfoResp = AjaxResult.error(exception.getMessage());
        } else {
            Map<String, String> params = getParameterStringMap(request);
            logger.warn("Not defined error occupted. params: " + params.toString(), ex);
            errorInfoResp = AjaxResult.error("服务器错误");
        }

        try {
            response.setContentType("application/json;charset=UTF-8");
            response.setCharacterEncoding("utf-8");
            response.getWriter().println(JSONObject.toJSONString(errorInfoResp));
        } catch (IOException e) {
            logger.warn("异常处理，返回结果出错", e);
        }

        return null;
    }

    public static Boolean isAjax(HttpServletRequest req) {
        return req.getHeader("X-Requested-With") != null
                && "XMLHttpRequest".equals(req.getHeader("X-Requested-With").toString());
    }

    // 返回值类型为Map<String, String>
    public static Map<String, String> getParameterStringMap(HttpServletRequest request) {
        Map<String, String[]> properties = request.getParameterMap();// 把请求参数封装到Map<String,

        Map<String, String> returnMap = new HashMap<String, String>();
        String name = "";
        String value = "";
        for (Map.Entry<String, String[]> entry : properties.entrySet()) {
            name = entry.getKey();
            String[] values = entry.getValue();
            if (null == values) {
                value = "";
            } else if (values.length > 1) {
                for (int i = 0; i < values.length; i++) { // 用于请求参数中有多个相同名称
                    value = values[i] + ",";
                }
                value = value.substring(0, value.length() - 1);
            } else {
                value = values[0];// 用于请求参数中请求参数名唯一
            }
            returnMap.put(name, value);
        }
        return returnMap;
    }
}
